﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;

using System.Xml.Linq;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;

/// <summary>
/// Summary description for ImageUtils
/// </summary>
/// 
namespace WebMVC.Utils
{
    public class ImageUtils
    {

        public static Boolean IsImage(Image image, int maxWidth, int maxHeight, int minWidth, int minHeight, params ImageFormat[] formats)
        {

            if (image.PhysicalDimension.Height > maxHeight || image.PhysicalDimension.Width > maxWidth)
            {
                return false;
            }

            if (image.PhysicalDimension.Height < minHeight || image.PhysicalDimension.Width < minWidth)
            {
                return false;
            }

            if ((image.PhysicalDimension.Width / image.PhysicalDimension.Height) > 4 ||
                (image.PhysicalDimension.Height / image.PhysicalDimension.Width) > 4)
            {
                return false;
            }

            var res = false;
            foreach (var imgFormat in formats)
            {
                res = res | image.RawFormat.Equals(imgFormat);
            }
            return res;
        }

        public static bool IsNormalJpeg(Stream fileStream)
        {
            try
            {
                using (var image = Image.FromStream(fileStream))
                {
                    return IsImage(image,2000, 2000, 10, 10, ImageFormat.Jpeg);
                }
            }
            catch (Exception)
            {
                return false;
            }
            
        }

        public static bool IsNormalPng(Stream fileStream)
        {
            try
            {
                using (var image = Image.FromStream(fileStream))
                {
                    return IsImage(image,2000, 2000, 10, 10, ImageFormat.Png);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool IsNormalAvatarJpegOrPng(Stream fileStream)
        {
            try
            {
                using (var image = Image.FromStream(fileStream))
                {
                    return IsImage(image, 1500, 1500, 110, 80, ImageFormat.Png, ImageFormat.Jpeg);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool IsNormalSalesJpegOrPng(Stream fileStream)
        {
            try
            {
                using (var image = Image.FromStream(fileStream))
                {
                    return IsImage(image, 3000, 3000, 300, 200, ImageFormat.Png, ImageFormat.Jpeg);
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}